package main

import (
	"bufio"
	"fmt"
	"github.com/antchfx/htmlquery"
	"github.com/ykallan/requests"
	"net/url"
	"os"
	"strconv"
	"strings"
)

func downloadNovel(name string, url string) {
	headers := requests.Headers{
		"User-Agent":                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
		"Referer":                   "http://www.siluwx.org/",
		"Upgrade-Insecure-Requests": "1",
	}
	response := requests.Get(url, headers)
	fmt.Println(response.Text)
	fmt.Println(response.StatusCode)
	fileName := fmt.Sprintf("./%s.zip", name)

	file, err := os.Create(fileName)
	if err != nil {
		fmt.Println("创建文件出错:", err.Error())
		return
	}
	defer file.Close()
	_, err = file.Write(response.Bytes)
	if err != nil {
		fmt.Println("写入文件出错:", err.Error())
		return
	}

	// 确保所有数据都写入磁盘
	err = file.Sync()
	if err != nil {
		fmt.Println("写入磁盘出错:", err.Error())
		return
	}

	fmt.Println("写入文件完成")

}

func downloadNovelByIndex(input2 string, names []string, links []string) {

	// http://download.siluwx.org/down/101/101154/all.zip
	preRequestUrl := "http://www.siluwx.org/downLoadfile/%s/"
	baseUrl := "http://download.siluwx.org/down/"
	inputInt, err := strconv.Atoi(strings.TrimSpace(input2))
	if err != nil {
		fmt.Printf("输入选项有误:%s", err.Error())
		return
	}

	if len(links) < inputInt {
		fmt.Println("输入序号有误", inputInt)
		return
	}
	link := links[inputInt]
	link = strings.Replace(link, "/book/", "", -1)
	link = strings.Replace(link, "/", "", -1)
	prefix := link[:3]
	newUrl := baseUrl + prefix + "/" + link + "/all.zip"
	newName := names[inputInt]
	preReqUrl := fmt.Sprintf(preRequestUrl, link)
	requests.Get(preReqUrl)
	fmt.Println(newUrl)
	downloadNovel(newName, newUrl)

}

func searchNovelName(input string) {

	reqUrl := "http://www.siluwx.org/Search?wd="
	reqUrl += url.QueryEscape(input)

	response := requests.Get(reqUrl)

	//fmt.Println(response.Text[:200])
	//fmt.Println(response.Text)
	names := response.Xpath("//div[@class=\"panel-body\"]/div/div/a/h2/text()").Getall()
	descS := response.Xpath("//div[@class=\"panel-body\"]/div/div/p[last()]/text()").Getall()
	resp, _ := htmlquery.Parse(strings.NewReader(response.Text))
	//urls := response.Xpath("//div[@class=\"panel-body\"]/div/a/@href").Getall()
	urls := htmlquery.Find(resp, "//div[@class=\"panel-body\"]/div/a/@href")
	//fmt.Println(names)
	links := []string{}

	for _, oneUrl := range urls {
		realUrl := htmlquery.InnerText(oneUrl)
		links = append(links, realUrl)
	}
	//fmt.Println(links)
	found := 0
	if len(names) > 0 {
		found = 1
	}
	for i := 0; i < len(names); i++ {
		name := names[i]
		desc := descS[i]
		if len(desc) > 70 {
			desc = desc[:70]
		}
		fmt.Printf("序号:[%d], 《%s》%s\n", i, name, desc)
	}
	if found == 0 {
		fmt.Println("没有找到小说,返回首页")
		return
	}
	fmt.Print("请输入需要进行下载:")
	reader := bufio.NewReader(os.Stdin)
	input2, err := reader.ReadString('\n')

	if input2 == "exit" {
		fmt.Println("退出系统")
		os.Exit(0)
		return
	}

	input2 = strings.TrimSpace(input2)
	if err != nil || len(input2) == 0 {
		fmt.Println("读取输入出错：", err)
		return
	}
	fmt.Println("开始下载", input2)
	downloadNovelByIndex(input2, names, links)

	return

}

func processInputString(input string) {
	fmt.Println("你输入的选项是：", input)
	if input == "exit" {
		os.Exit(0)
	}

	if len(input) <= 0 {
		return
	}
	searchNovelName(input)
}

func main() {
	fmt.Println("小说下载工具")
	for {
		reader := bufio.NewReader(os.Stdin)
		input, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("读取输入出错：", err)
			return
		}
		input = strings.TrimSpace(input)
		processInputString(input)
	}

}
